<?php
/**
 * 掌灵支付
 */

namespace app\api\service\payment;

use app\api\service\ApiPayment;
use app\common\library\exception\OrderException;
use app\api\service\payment\Palmfpay\ItpPay as ItpPay;

class Palmfpay extends ApiPayment
{
    public function alipay($order)
    {
        return $this->requestApi($order);
    }

    public function wechat($order)
    {
        return $this->requestApi($order, '2000000002');
    }

    public function wechat_h5($order)
    {
        return $this->requestApi($order, 'wechat_h5');
    }

    public function alipay_h5($order)
    {
        return $this->requestApi($order, 'alipay_h5');
    }

    public function ysf($order)
    {
        return $this->requestApi($order, 'ysf');
    }

    public function requestApi($order, $payChannelId = '2000000002')
    {
        $client  = new ItpPay($this->config);
        $parameter=array(
            "amount"         => $order['amount'] * 100,//[必填]订单总金额，单位(分)
            "appid"          =>$this->config["app_id"],//[必填]//交易发起所属app
            "body"           => "body",//[必填]商品描述
            "clientIp"       => $_SERVER['REMOTE_ADDR'],//[必填]客户端IP
            "mchntOrderNo"   => $order['trade_no'],//[必填]商户订单号，必须唯一性
            "notifyUrl"      =>"{$_SERVER['REQUEST_SCHEME']}://{$_SERVER['HTTP_HOST']}/notify/Palmfpay",//[必填]订单支付结果异步通知地址，用于接收订单支付结果通知，必须以http或https开头
            "returnUrl"      =>"{$_SERVER['REQUEST_SCHEME']}://{$_SERVER['HTTP_HOST']}/success",//[必填]订单支付结果同步跳转地址，用于同步跳转到商户页面，必须以http或https开头
            "subject"        =>"subject",//[必填]商品名称
            "openId"         => "",
            "version"        =>"api_NoEncrypt",//接口版本号，值为pc_NoEncrypt时,则明天平台返回商户参数时，不进行RSA加密
            "payChannelId"   =>$payChannelId,//支付渠道id
            "description"    =>"",
            "extra"          =>"",
            "expireMs"       =>"",
            "cpChannel"      =>"",
            "currency"       =>"",
            "openId"         =>""
        );

        try {
            $orderInfo=$client->getOrderInfo($parameter);
            $orderInfo = str_replace("+","%2B",$orderInfo);
            $data = $client->curl("http://trans.palmf.cn/sdk/api/v1.0/cli/order_api/0", "orderInfo=".$orderInfo);
            $dataArr = json_decode($data, true);
            if (is_array($dataArr) && !empty($dataArr['extra'])){
                $extra = explode('&', $dataArr['extra']);
                $extraArr = [];
                foreach($extra as $item) {
                    $itemArr = explode('=', $item);
                    if (!empty($itemArr[0] && !empty($itemArr[1]))) {
                        $extraArr[$itemArr[0]] = $itemArr[1];
                    }
                }


                return [
                    'order_id' => $order['out_trade_no'],
                    'pay_seq' => $order['trade_no'],
                    'pay_url' => $extraArr['code_img_url'],
                    'pay_app_url' => $extraArr['code_url']
                ];
            }
        } catch (\Exception $e) {
            // print $e->getMessage();
        }

        return false;
    }

    public function notify()
    {
        return $this->verifyOrderNotify();
    }

    /**
     * 回调验签.
     *
     *
     * @return array
     *
     * @throws OrderException
     */
    private function verifyOrderNotify()
    {
        $xml = file_get_contents('php://input');
        file_put_contents("/tmp/Palmfpay.log", var_export($_POST, true), FILE_APPEND);
        file_put_contents("/tmp/Palmfpay_get.log", var_export($_GET, true), FILE_APPEND);
        file_put_contents("/tmp/Palmfpay_input.log", $xml, FILE_APPEND);


        $parameter = json_decode($xml, true);
        $signature = $parameter["signature"];
        // unset($parameter["signature"]);
        // $itpPay = new itpPay($this->config);
        // $signature_local=$itpPay->setSignature($parameter);

        if ($parameter["paySt"] == "2"){
            return array(
                'trade_no' => $parameter["mchntOrderNo"],
            );
        } 

        return false;
    }

}
